package com.vf.s.mvc.biz.controller;

import java.io.File;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.vf.core.controller.BaseController;
import com.vf.core.util.UuidUtil;
import com.vf.s.common.model.biz.BizVector;
import com.vf.s.common.plugins.shiro.ShiroKit;
import com.vf.s.common.plugins.shiro.SimpleUser;

public class BizVectorController extends BaseController{

	public void index() {
		render("list.html");
	}
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String name = getPara("name");
		String isPublic = getPara("isPublic");
		
		String userId="";
		SimpleUser simpleUser = ShiroKit.getLoginUser();
		if (simpleUser != null) {
			userId=simpleUser.getId();
		}
		
		String select = " select *  ";
		String sqlExceptSelect = " from " + BizVector.TABLE_NAME + " o  where 1=1 ";
		
		if(StrKit.equals("1",isPublic)) {
			sqlExceptSelect += " and o.createUserId = '" + userId + "'   ";	
		}
		else if(StrKit.equals("0",isPublic)) {
			sqlExceptSelect += " and o.isPublic = '0'   ";	
		}else {
			if(!StrKit.equals(simpleUser.getUsername(),"system")) {
				sqlExceptSelect += " and ( o.createUserId = '" + userId + "' or  o.isPublic = '0' ) ";
			}
		}
		
		if (!StrKit.isBlank(name)) {
			sqlExceptSelect += " and o.name like '%" + name + "%'  ";
		}
		
		Page<BizVector> page = BizVector.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
	private String rootPath = PathKit.getWebRootPath();
	public void upload() {
		UploadFile uploadFile = getFile();
		try {
			String path = "/upload/vector/"+System.currentTimeMillis()+"/" + uploadFile.getFileName().replace(" ", "");
			File file = new File(rootPath+path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			String fileName=uploadFile.getFileName();
			BizVector bizKml = new BizVector();
			bizKml.setId(UuidUtil.getUUID());
			bizKml.setName(fileName);
			bizKml.setFormat(fileName.substring(fileName.lastIndexOf(".") + 1));
			bizKml.setPath(path);
			if(uploadFile.getFile().renameTo(file) && bizKml.save()) {
				renderSuccess("上传成功！");
			}else {
				renderError("上传失败！");
			}
		} catch (Exception e) {
			renderError(e.getMessage());
		}
	}
	
	public void delete() throws Exception {
		String id = getPara("id");
		BizVector model = BizVector.dao.findById(id);
		if (model != null) {
			if (model.delete()) {
				File file = new File(rootPath+model.getPath());
				if (file.exists()) {
					file.delete();
				}
				renderSuccess("删除成功！");
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
}
